package com.teangtang.fly.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.teangtang.fly.dto.RegisterDTO;
import com.teangtang.fly.entity.Admin;
import com.teangtang.fly.entity.Traveller;
import com.teangtang.fly.entity.user;
import com.teangtang.fly.service.JWTService;
import com.teangtang.fly.service.loginService;
import com.teangtang.fly.service.TravellerService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/")
public class LoginAndRegisterController {
    @Autowired
    private JWTService jwtService;
    @Autowired
    private loginService loginService;
    @Autowired
    private TravellerService travellerService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login/admin")
    public ResponseEntity<String> adminLogin(@RequestBody Admin admin) {
        String username = admin.getUsername();
        String password = admin.getPassword();
        if (loginService.adminLogin(username, password)) {
            String token = jwtService.generateAdminToken(admin);
            return ResponseEntity.ok(token);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }
    @GetMapping("/info")
    public ResponseEntity<?> getinfo(@RequestParam("token") String token) {
        Claims claims = JWTService.getClaimsByToken(token);
        String userName = claims.get("userName", String.class);
        String userType = claims.get("userType", String.class);
        user user = new user();
        user.setUsername(userName);
        user.setUserType(userType);
        return ResponseEntity.ok(user);
    }

    @PostMapping("/sendVerificationCode")
    public ResponseEntity<String> sendVerificationCode(@RequestBody Map<String, String> requestBody, HttpServletRequest request) {
        if (HttpMethod.OPTIONS.name().equals(request.getMethod())) { // 处理 OPTIONS 请求
            return ResponseEntity.ok()
                    .header("Access-Control-Allow-Origin", "http://192.168.1.8:8081/", "http://localhost:8081/") // 设置允许的源
                    .header("Access-Control-Allow-Methods", "POST") // 设置允许的请求方法
                    .header("Access-Control-Allow-Headers", "content-type") // 设置允许的请求头
                    .build();
        }
        String phoneNumber = requestBody.get("phoneNumber");

        String signName = "特昂糖";

        String templateCode = "SMS_468620018";
        // 生成验证码逻辑（这里简单模拟生成6位随机数作为验证码）
        String verificationCode = String.format("%06d", (int)(Math.random() * 900000) + 100000);
        String templateParam = "{\"code\":\"" + verificationCode + "\"}";

        // 发送短信
        SendSmsResponse response = loginService.sendSms(phoneNumber, signName, templateCode, templateParam);
        if (response != null && "OK".equals(response.getCode())) {
            // 存储验证码到Redis，有效期5分钟
            stringRedisTemplate.opsForValue().set(phoneNumber, verificationCode, 5, TimeUnit.MINUTES);
            return ResponseEntity.ok("验证码已发送");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("验证码发送失败！");
        }
    }
    @PostMapping("/login/traveller/byPhone/VerificationCode")
    public ResponseEntity<?> userPhoneVerificationCodeLogin(@RequestBody Map<String, String> requestBody) {
        String phoneNumber = requestBody.get("phone");
        String verificationCode = requestBody.get("phoneCode");

        if (loginService.verifyCode(phoneNumber, verificationCode)) {
            // 验证成功，检查用户是否存在
            Traveller existingTraveller = travellerService.findByPhone(phoneNumber);
            if (existingTraveller != null) {
                // 用户已存在，登录
                String token = jwtService.generateTravellerToken(existingTraveller);
                return ResponseEntity.ok(token);
            } else {
                // 用户不存在，返回注册信息
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户不存在，请先注册");
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("验证码错误");
        }
    }
    @PostMapping("/login/traveller/byPassword")
    public ResponseEntity<?> userPhonePasswordLogin(@RequestBody Map<String, String> requestBody) {
        String username = requestBody.get("username");
        String password = requestBody.get("password");
        if(username.length()==11){
            Traveller existingTraveller = travellerService.findByPhone(username);
            if (existingTraveller != null && existingTraveller.getPassword().equals(password)) {
                // 验证成功，检查用户是否存在
                String token = jwtService.generateTravellerToken(existingTraveller);
                return ResponseEntity.ok(token);
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("手机号或密码错误");
            }
        }
        else if(username.length()==18){
            Traveller existingTraveller = travellerService.findByIdCardAndIdCardType(username, "身份证");
            if (existingTraveller != null && existingTraveller.getPassword().equals(password)) {
                // 验证成功，检查用户是否存在
                String token = jwtService.generateTravellerToken(existingTraveller);
                return ResponseEntity.ok(token);
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("身份证或密码错误");
            }
        }
        else{
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
        }
    }
    @PostMapping("/register/traveller")
    public ResponseEntity<String> registerTraveller(@RequestBody RegisterDTO registerDTO) {
        String phoneNumber = registerDTO.getPhone();
        String verificationCode = registerDTO.getVerificationCode();
        Traveller traveller = new Traveller();
        traveller.setPhone(phoneNumber);
        traveller.setPassword(registerDTO.getPassword());
        traveller.setUsername(registerDTO.getUsername());
        traveller.setName(registerDTO.getUsername());
        traveller.setGender(registerDTO.getSex());
        traveller.setIdCard(registerDTO.getIdCard());
        traveller.setIdCardType(registerDTO.getIdCardType());
        traveller.setStatus("正常");
        if (loginService.verifyCode(phoneNumber, verificationCode)) {
            // 验证成功，检查用户是否存在
            Traveller existingTraveller = travellerService.findByIdCardAndIdCardType(traveller.getIdCard(), traveller.getIdCardType());
            if (existingTraveller != null) {
                // 用户已存在，登录
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户已存在，请直接登录");
            } else {
                // 用户不存在，注册
                travellerService.save(traveller);
                return ResponseEntity.ok("注册成功");
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("验证码错误");
        }
    }
}
